package com.lv.service.dialog

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.ScrollView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ScreenUtils
import com.lv.common.imp.OnPosition4Listener
import com.lv.common.imp.OnPositionTListener
import com.lv.common.utils.showToast
import com.lv.common.widget.ReboundHScrollView
import com.lv.common.widget.linkbar.ZFlowLayout
import com.lv.service.R
import com.lv.service.adapter.AddressAreaAdapter
import com.lv.service.adapter.AddressCityAdapter
import com.lv.service.adapter.AddressProvinceAdapter
import com.lv.service.adapter.AddressTownAdapter
import com.lv.service.bean.TelFourCategoryBean
import com.lv.service.bean.TelSecondCategoryBean
import com.lv.service.bean.TelThirdCategoryBean
import com.lv.service.room.address.AddressBean
import com.lv.service.room.address.ReceiptAddressItem
import com.lxj.xpopup.core.BottomPopupView

/**
 * 作者： ygx
 * 创建日期：2022/10/10 10:32 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 *
 *
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：四级地区选择(可在任意级输出结果)
 */
class AddressFourTypeCardPopupView(
    private val mContext: Context,
    private val mOpenBeans: List<AddressBean>? = null,
    private val mAllBeans: List<ReceiptAddressItem>? = null,
    private var currentTopProvin: Int = -1,
    private var mCurrentProvin: Int = 0,
    private var mCurrentCity: Int = 0,
    private var mCurrentArea: Int = 0,
    private var mCurrentTown: Int = 0,
    private var mTitle: String = "请选择地区",
    private var mTabCount: TABCOUNT = TABCOUNT.ALL,
    private val mPosition4Listener: OnPosition4Listener? = null,
) :
    BottomPopupView(mContext) {
    private var name = ""
    private var rvProvince: RecyclerView? = null
    private var rvCity: RecyclerView? = null
    private var rvArea: RecyclerView? = null
    private var rvTown: RecyclerView? = null

    private var finish: Boolean? = false
    private var viewTop: View? = null
    private var tvTitle: TextView? = null
    private var llTv1: RelativeLayout? = null
    private var llTv2: RelativeLayout? = null
    private var llTv3: RelativeLayout? = null
    private var llTv4: RelativeLayout? = null
    private var mScrollView: ReboundHScrollView? = null
    private var mFlowLayout: ZFlowLayout? = null
    private var mTv1: TextView? = null
    private var mTv2: TextView? = null
    private var mTv3: TextView? = null
    private var mTv4: TextView? = null
    private var mTvSure: TextView? = null
    private var v1: View? = null
    private var v2: View? = null
    private var v3: View? = null
    private var v4: View? = null
    private val mBeans = mutableListOf<ReceiptAddressItem>()
    private val mCityBeans = mutableListOf<TelSecondCategoryBean>()
    private val mAreaBeans = mutableListOf<TelThirdCategoryBean>()
    private val mTownBeans = mutableListOf<TelFourCategoryBean>()
    private val mRvs = mutableListOf<RecyclerView?>()
    private val mVs = mutableListOf<View?>()
    private val mLLs = mutableListOf<RelativeLayout?>()

    private var mAdapter: AddressProvinceAdapter? = null
    private var mCityAdapter: AddressCityAdapter? = null
    private var mAreaAdapter: AddressAreaAdapter? = null
    private var mTownAdapter: AddressTownAdapter? = null

    //tempPosition
    private var currentProvin: Int = -1
    private var currentCity: Int = -1
    private var currentArea: Int = -1
    private var currentTown: Int = -1

    private var isFrist = true
    private var isEditor = false
    private val mViewList = mutableListOf<View>()

    override fun getImplLayoutId(): Int {
        return R.layout.address_card_popup
    }

    override fun onCreate() {
        super.onCreate()
        findIds()
        initView()
        initEvnet()
        setFlowData()
    }

    private fun setFlowData() {
        mViewList.clear()
        if (!mOpenBeans.isNullOrEmpty()) {
            for (i in 0 until mOpenBeans.size) {
                val textChild = LayoutInflater.from(mContext)
                    .inflate(
                        R.layout.text_tag_card_address_layout,
                        mFlowLayout, false
                    ) as TextView
                textChild.text = mOpenBeans[i].telSecondCategories?.get(0)?.name
                mViewList.add(textChild)
            }
            if (currentTopProvin != -1) {
                mViewList[currentTopProvin].setBackgroundResource(com.lv.common.R.drawable.bg_tab_eb613d_14)
            }

            mFlowLayout?.setChildren(mViewList)
            mFlowLayout?.setOnTagClickListener { view, position ->
                mViewList.forEach { viewItem ->
                    viewItem.setBackgroundResource(com.lv.common.R.drawable.bg_f9_15)
                }
                mViewList[position].setBackgroundResource(com.lv.common.R.drawable.bg_tab_eb613d_14)
                mPosition4Listener?.onClick(position, -1, -1, -1)
                dismiss()
            }
        }

    }

    private fun initData() {
        if (currentProvin == -1) {
            mTv1?.text = "请选择"
            llTv2?.visibility = GONE
            llTv3?.visibility = GONE
            llTv4?.visibility = GONE
            rvCity?.visibility = GONE
            rvArea?.visibility = GONE
            rvTown?.visibility = GONE
            for (i in 0 until mBeans.size) {
                mBeans[i].isShow = false
            }
            rvProvince?.visibility = visibility

            mAdapter?.notifyDataSetChanged()
        } else {
            if (mCityBeans.isEmpty() || isEditor) {//编辑时 初始化选中位置
                isEditor = true
                finish = true
                //recycler有头，位置要加 1
//                if (isFrist) {
//                    currentProvin += 1
//                    currentCity += 1
//                    currentArea += 1
//                    currentTown += 1
//                    isFrist = false
//                }
                mCurrentProvin = currentProvin
                mCurrentCity = currentCity
                mCurrentArea = currentArea
                mCurrentTown = currentTown
                val telSecondCategories = mBeans[currentProvin].telSecondCategories
                mCityBeans.clear()
                telSecondCategories?.let {
                    mCityBeans.addAll(telSecondCategories)
                }
                val telThirdCategories = mCityBeans[currentCity].telThirdCategories
                mAreaBeans.clear()
                telThirdCategories?.let {
                    mAreaBeans.addAll(telThirdCategories)
                }
                val telFourCategories = mAreaBeans[currentArea].telFourCategories
                mTownBeans.clear()
                telFourCategories?.let {
                    mTownBeans.addAll(telFourCategories)
                }
                mBeans.forEach { item ->
                    if (item.isShow) {
                        item.isShow = false
                    }
                }
                mCityBeans.forEach { item ->
                    if (item.isShow) {
                        item.isShow = false
                    }
                }
                mAreaBeans.forEach { item ->
                    if (item.isShow) {
                        item.isShow = false
                    }
                }
                mTownBeans.forEach { item ->
                    if (item.isShow) {
                        item.isShow = false
                    }
                }
                llTv1?.visibility = View.VISIBLE
                llTv2?.visibility = View.VISIBLE
//                v1?.visibility = View.GONE
                mTv1?.visibility = View.VISIBLE
                mTv2?.visibility = View.VISIBLE
                mTv1?.text = mBeans[mCurrentProvin].name
                mTv2?.text = mCityBeans[mCurrentCity].name
                mBeans[mCurrentProvin].isShow = true
                mAdapter?.notifyDataSetChanged()
                mCityBeans[mCurrentCity].isShow = true
                mCityAdapter?.notifyDataSetChanged()
                when (mTabCount) {
                    TABCOUNT.CITY -> {
                        v2?.visibility = View.VISIBLE
                        setTabClickLLVis(1)
                    }

                    TABCOUNT.TOWN -> {
                        llTv3?.visibility = View.VISIBLE
//                        v2?.visibility = View.GONE
//                        v3?.visibility = View.VISIBLE
                        setTabClickLLVis(2)
                        mTv3?.visibility = View.VISIBLE
                        mTv3?.text = mAreaBeans[mCurrentArea].name
                        mAreaBeans[mCurrentArea].isShow = true
                        mAreaAdapter?.notifyDataSetChanged()
                    }

                    else -> {
                        llTv3?.visibility = View.VISIBLE
                        llTv4?.visibility = View.VISIBLE
//                        v2?.visibility = View.GONE
//                        v3?.visibility = View.GONE
//                        v4?.visibility = View.VISIBLE
                        setTabClickLLVis(3)
                        mTv3?.visibility = View.VISIBLE
                        mTv4?.visibility = View.VISIBLE
                        mTv3?.text = mAreaBeans[mCurrentArea].name
                        mTv4?.text = mTownBeans[mCurrentTown].name
                        mAreaBeans[mCurrentArea].isShow = true
                        mAreaAdapter?.notifyDataSetChanged()
                        mTownBeans[mCurrentTown].isShow = true
                        mTownAdapter?.notifyDataSetChanged()
                        rvTown?.visibility = View.VISIBLE
                    }

                }
                if (currentCity == 0) {
                    mTv3?.visibility = View.GONE
                    mTv4?.visibility = View.GONE
                    setTabClickLLVis(1)
                } else if (currentArea == 0) {
                    mTv4?.visibility = View.GONE
                    setTabClickLLVis(2)
                }

            }
        }
    }

    private fun findIds() {
        mScrollView = findViewById<ReboundHScrollView>(R.id.scroll_view)
        mFlowLayout = findViewById<ZFlowLayout>(R.id.z_flow)
        rvProvince = findViewById<RecyclerView>(R.id.rv_province)
        rvCity = findViewById<RecyclerView>(R.id.rv_city)
        rvArea = findViewById<RecyclerView>(R.id.rv_area)
        rvTown = findViewById<RecyclerView>(R.id.rv_town)
        viewTop = findViewById<View>(R.id.view_top)
        tvTitle = findViewById<TextView>(R.id.tv_title)
        llTv1 = findViewById<RelativeLayout>(R.id.ll_tv1)
        mTv1 = findViewById<TextView>(R.id.tv_1)
        llTv2 = findViewById<RelativeLayout>(R.id.ll_tv2)
        mTv2 = findViewById<TextView>(R.id.tv_2)
        llTv3 = findViewById<RelativeLayout>(R.id.ll_tv3)
        mTv3 = findViewById<TextView>(R.id.tv_3)
        llTv4 = findViewById<RelativeLayout>(R.id.ll_tv4)
        mTv4 = findViewById<TextView>(R.id.tv_4)
        mTvSure = findViewById<TextView>(R.id.tv_sure)
        v1 = findViewById<View>(R.id.view_1)
        v2 = findViewById<View>(R.id.view_2)
        v3 = findViewById<View>(R.id.view_3)
        v4 = findViewById<View>(R.id.view_4)
        mRvs.clear()
        mRvs.add(rvProvince)
        mRvs.add(rvCity)
        mRvs.add(rvArea)
        mRvs.add(rvTown)
        mVs.clear()
        mVs.add(v1)
        mVs.add(v2)
        mVs.add(v3)
        mVs.add(v4)
        mLLs.clear()
        mLLs.add(llTv1)
        mLLs.add(llTv2)
        mLLs.add(llTv3)
        mLLs.add(llTv4)

    }


    private fun initView() {
        tvTitle?.text = mTitle
        mAdapter = AddressProvinceAdapter(mBeans)
        rvProvince?.adapter = mAdapter
        val topHeader = View.inflate(context, R.layout.item_address_header, null)
        mAdapter?.addHeaderView(topHeader)

        val secondHeader = View.inflate(context, R.layout.item_address_header, null)
        mCityAdapter = AddressCityAdapter(mCityBeans)
        rvCity?.adapter = mCityAdapter
        mCityAdapter?.addHeaderView(secondHeader)
        when (mTabCount) {
            TABCOUNT.CITY -> {}
            TABCOUNT.TOWN -> {
                val areaHeader = View.inflate(context, R.layout.item_address_header, null)
                mAreaAdapter = AddressAreaAdapter(mAreaBeans)
                rvArea?.adapter = mAreaAdapter
                mAreaAdapter?.addHeaderView(areaHeader)
            }

            TABCOUNT.ALL -> {
                val areaHeader = View.inflate(context, R.layout.item_address_header, null)
                mAreaAdapter = AddressAreaAdapter(mAreaBeans)
                rvArea?.adapter = mAreaAdapter
                mAreaAdapter?.addHeaderView(areaHeader)

                val townHeader = View.inflate(context, R.layout.item_address_header, null)
                mTownAdapter = AddressTownAdapter(mTownBeans)
                rvTown?.adapter = mTownAdapter
                mTownAdapter?.addHeaderView(townHeader)
            }

        }


    }

    private fun initEvnet() {

        viewTop?.setOnClickListener {

//            initPreData()
            dismiss()
        }
        findViewById<ImageView>(R.id.iv_close).setOnClickListener {

//            initPreData()
            dismiss()
        }

        mAdapter?.onViewClickListener = OnPositionTListener { position, data ->
            finish = false
            mBeans.forEach { item ->
                item.isShow = false
                item.telSecondCategories?.forEach { item2 ->
                    item2.isShow = false
                    item2.telThirdCategories?.forEach { item3 ->
                        item3.isShow = false
                        item3.telFourCategories?.forEach { item4 ->
                            item4.isShow = false
                        }
                    }
                }
            }
            mAdapter?.notifyDataSetChanged()
            mBeans[position - 1].isShow = true
            mAdapter?.notifyItemChanged(position)
            currentProvin = position - 1
            mTv1?.text = mBeans[currentProvin].name
            setAdapterClick_TabVis(0)
            mTv2?.text = "全部"
            currentCity = 0

            val telSecondCategories = data.telSecondCategories
            if (!telSecondCategories.isNullOrEmpty()) {
                telSecondCategories[0].isShow = true
            }
            telSecondCategories?.let {
                mCityBeans.clear()
                mCityBeans.addAll(telSecondCategories)
                mCityAdapter?.notifyDataSetChanged()
            }
        }
        mCityAdapter?.onViewClickListener = OnPositionTListener { position, data ->
            finish = false
            mCityBeans.forEach { item2 ->
                item2.isShow = false
                item2.telThirdCategories?.forEach { item3 ->
                    item3.isShow = false
                    item3.telFourCategories?.forEach { item4 ->
                        item4.isShow = false
                    }
                }
            }
            mCityAdapter?.notifyDataSetChanged()
            mCityBeans[position - 1].isShow = true
            mCityAdapter?.notifyItemChanged(position)
            currentCity = position - 1
            mTv2?.text = mCityBeans[currentCity].name
            if (mTabCount == TABCOUNT.CITY) {
                finish = true
                return@OnPositionTListener
            }
            mTv3?.text = "全部"
            if (position != 1) {
                setAdapterClick_TabVis(1)
                mTv3?.visibility = View.VISIBLE
            } else {
                mTv3?.visibility = View.GONE
                mTv4?.visibility = View.GONE
            }
            currentArea = 0
            val thirdCategory = data.telThirdCategories
            if (!thirdCategory.isNullOrEmpty()) {
                thirdCategory[0].isShow = true
            }
            thirdCategory?.let {
                mAreaBeans.clear()
                mAreaBeans.addAll(thirdCategory)
                mAreaAdapter?.notifyDataSetChanged()
            }
        }
        mAreaAdapter?.onViewClickListener = OnPositionTListener { position, data ->
            finish = false
            mAreaBeans.forEach { item3 ->
                item3.isShow = false
                item3.telFourCategories?.forEach { item4 ->
                    item4.isShow = false
                }
                mAreaAdapter?.notifyDataSetChanged()
            }
            mAreaBeans[position - 1].isShow = true
            mAreaAdapter?.notifyItemChanged(position)
            currentArea = position - 1
            mTv3?.text = mAreaBeans[currentArea].name
            if (mTabCount == TABCOUNT.TOWN) {
                finish = true
                return@OnPositionTListener
            }
            mTv4?.text = "全部"
            if (position != 1) {
                setAdapterClick_TabVis(2)
                mTv4?.visibility = View.VISIBLE
            } else {
                mTv4?.visibility = View.GONE
            }
            currentTown = 0
            val telFourCategory = data.telFourCategories
            if (!telFourCategory.isNullOrEmpty()) {
                telFourCategory[0].isShow = true
            }
            telFourCategory?.let {
                mTownBeans.clear()
                mTownBeans.addAll(telFourCategory)
                mTownAdapter?.notifyDataSetChanged()
            }
            mScrollView?.fullScroll(ScrollView.FOCUS_RIGHT)

        }
        mTownAdapter?.onViewClickListener = OnPositionTListener { position, data ->
            finish = true
            mTownBeans.forEach { item ->
                item.isShow = false
            }
            mTownAdapter?.notifyDataSetChanged()
            mTownBeans[position - 1].isShow = true
            mTownAdapter?.notifyItemChanged(position)
            currentTown = position - 1
            mTv4?.text = mTownBeans[currentTown].name
            if (position != 1) {
                setAdapterClick_TabVis(3)
            }
            mScrollView?.smoothScrollTo(ScreenUtils.getScreenWidth() / 2, 0)

        }
        llTv1?.setOnClickListener {
            setTabClickLLVis(0)
        }
        llTv2?.setOnClickListener {
            setTabClickLLVis(1)
        }
        llTv3?.setOnClickListener {
            setTabClickLLVis(2)
        }
        llTv4?.setOnClickListener {
            setTabClickLLVis(3)
        }
        mTvSure?.setOnClickListener {
//            if (finish == false) {
//                return@setOnClickListener showToast("请完成地区选择")
//            }
            if (currentProvin == -1) {
                showToast("请完成地区选择")
                return@setOnClickListener
            }
            mCurrentProvin = currentProvin
            mCurrentCity = currentCity
            mCurrentArea = currentArea
            mCurrentTown = currentTown
            mPosition4Listener?.onClick(mCurrentProvin, mCurrentCity, mCurrentArea, mCurrentTown)
            dismiss()

        }

    }

    private fun setTabClickLLVis(position: Int) {
        mVs.forEach { it?.visibility = View.GONE }
        mRvs.forEach { it?.visibility = View.GONE }
        mVs[position]?.visibility = View.VISIBLE
        mRvs[position]?.visibility = View.VISIBLE


//        when (position) {
//            0 -> {
//
//            }
//
//
//        }
    }

    private fun setAdapterClick_TabVis(position: Int) {
        mVs.forEach { it?.visibility = View.GONE }
        mRvs.forEach { it?.visibility = View.GONE }
        mLLs[0]?.visibility = View.VISIBLE
        mLLs[1]?.visibility = View.VISIBLE
        when (position) {
            0 -> {
                mRvs[1]?.visibility = View.VISIBLE
                mVs[1]?.visibility = View.VISIBLE
                mLLs[2]?.visibility = View.GONE
                mLLs[3]?.visibility = View.GONE

            }

            1 -> {
                if (mTabCount == TABCOUNT.CITY) {
                    mRvs[1]?.visibility = View.VISIBLE
                    mVs[1]?.visibility = View.VISIBLE
                    mLLs[2]?.visibility = View.GONE
                    mLLs[3]?.visibility = View.GONE
                } else {
                    mRvs[2]?.visibility = View.VISIBLE
                    mVs[2]?.visibility = View.VISIBLE
                    mLLs[2]?.visibility = View.VISIBLE
                    mLLs[3]?.visibility = View.GONE
                }

            }

            2 -> {
                if (mTabCount == TABCOUNT.TOWN) {
                    mRvs[3]?.visibility = View.GONE
                    mLLs[3]?.visibility = View.GONE
                    mVs[3]?.visibility = View.VISIBLE
                } else {
                    mRvs[3]?.visibility = View.VISIBLE
                    mVs[3]?.visibility = View.VISIBLE
                    mLLs[2]?.visibility = View.VISIBLE
                    mLLs[3]?.visibility = View.VISIBLE
                }
            }

            3 -> {
                mRvs[3]?.visibility = View.VISIBLE
                mVs[3]?.visibility = View.VISIBLE
                mLLs[2]?.visibility = View.VISIBLE
                mLLs[3]?.visibility = View.VISIBLE
            }


        }
    }

    private fun initPreData() {
        rvProvince?.visibility = View.GONE
        rvCity?.visibility = View.GONE
        rvArea?.visibility = View.GONE
        rvTown?.visibility = View.GONE
        currentProvin = mCurrentProvin
        currentCity = mCurrentCity
        currentArea = mCurrentArea
        currentTown = mCurrentTown
        if (!mAllBeans.isNullOrEmpty()) {
            mBeans.clear()
            mBeans.addAll(mAllBeans)
            initData()
        }
    }


    override fun onShow() {
        super.onShow()
        initPreData()
    }

    private fun setDismissDialog() {
        dismiss()
    }


    override fun onDestroy() {
        super.onDestroy()
    }

    override fun beforeDismiss() {
        super.beforeDismiss()
    }

    enum class TABCOUNT {
        CITY, TOWN, ALL
    }

}